<template>
  <div class="user-management page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">用户管理</h1>
        <p class="page-subtitle">管理系统用户信息，包括普通用户和团长用户</p>
      </div>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-input
          v-model="searchForm.phone"
          placeholder="手机号"
          class="search-input"
          clearable
        />
        <el-input
          v-model="searchForm.nickname"
          placeholder="昵称"
          class="search-input"
          clearable
        />
        <el-select
          v-model="searchForm.isLeader"
          placeholder="用户类型"
          clearable
          class="type-select"
        >
          <el-option label="普通用户" value="0" />
          <el-option label="团长" value="1" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="userList"
        style="width: 100%"
        class="user-table"
        v-loading="loading"
        row-key="id"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="nickname"
          label="昵称"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="phone"
          label="手机号"
          width="130"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.phone">{{ row.phone }}</span>
            <span v-else class="no-phone">未绑定</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="isLeader"
          label="用户类型"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="row.isLeader === 1 ? 'success' : 'primary'"
              size="small"
            >
              {{ row.isLeader === 1 ? "团长" : "普通用户" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            <span>{{ getGenderText(row.gender) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100" align="right">
          <template #default="{ row }">
            <span class="points-value">{{ formatNumber(row.points) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 1 ? 'success' : 'danger'"
              size="small"
            >
              {{ row.status === 1 ? "正常" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="riskUser"
          label="风险用户"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.riskUser ? 'danger' : 'success'" size="small">
              {{ row.riskUser ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="注册时间"
          width="160"
          show-overflow-tooltip
        />

        <!-- 资金账户信息 -->
        <el-table-column label="可用余额" width="120" align="right">
          <template #default="{ row }">
            <div v-if="row.isLeader === 1">
              <span v-if="row.fundAccountVO" class="balance-value">
                {{ formatCurrency(row.fundAccountVO.balance) }}
              </span>
              <span v-else class="no-account">未开通</span>
            </div>
            <span v-else class="not-applicable">-</span>
          </template>
        </el-table-column>
        <el-table-column label="待入账金额" width="120" align="right">
          <template #default="{ row }">
            <div v-if="row.isLeader === 1 && row.fundAccountVO">
              <span class="pending-value">
                {{ formatCurrency(row.fundAccountVO.pendingIncome) }}
              </span>
            </div>
            <span v-else class="not-applicable">-</span>
          </template>
        </el-table-column>
        <el-table-column label="退款预留金" width="120" align="right">
          <template #default="{ row }">
            <div v-if="row.isLeader === 1 && row.fundAccountVO">
              <span class="reserve-value">
                {{ formatCurrency(row.fundAccountVO.refundReserve) }}
              </span>
            </div>
            <span v-else class="not-applicable">-</span>
          </template>
        </el-table-column>
        <el-table-column label="申请提现金额" width="130" align="right">
          <template #default="{ row }">
            <div v-if="row.isLeader === 1 && row.fundAccountVO">
              <span class="applying-value">
                {{ formatCurrency(row.fundAccountVO.applyingWithdrawal) }}
              </span>
            </div>
            <span v-else class="not-applicable">-</span>
          </template>
        </el-table-column>
        <el-table-column label="累计收入" width="120" align="right">
          <template #default="{ row }">
            <div v-if="row.isLeader === 1 && row.fundAccountVO">
              <span class="income-value">
                {{ formatCurrency(row.fundAccountVO.totalIncome) }}
              </span>
            </div>
            <span v-else class="not-applicable">-</span>
          </template>
        </el-table-column>
        <el-table-column label="累计提现" width="120" align="right">
          <template #default="{ row }">
            <div v-if="row.isLeader === 1 && row.fundAccountVO">
              <span class="withdrawn-value">
                {{ formatCurrency(row.fundAccountVO.totalWithdrawn) }}
              </span>
            </div>
            <span v-else class="not-applicable">-</span>
          </template>
        </el-table-column>

        <el-table-column label="开户时间" width="160" align="right">
          <template #default="{ row }">
            <div v-if="row.isLeader === 1 && row.fundAccountVO">
              <span class="withdrawn-value">
                {{ row.fundAccountVO.createdTime }}
              </span>
            </div>
            <span v-else class="not-applicable">-</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <!-- 团长且没有资金账户时显示开通按钮 -->
              <template v-if="row.isLeader === 1 && !row.fundAccountVO">
                <el-button
                  size="small"
                  type="primary"
                  @click="openFundAccount(row)"
                  class="action-btn"
                >
                  开通资金账户
                </el-button>
              </template>

              <!-- 查看详情按钮 -->
              <el-button
                size="small"
                type="info"
                @click="viewUserDetail(row)"
                class="action-btn"
              >
                详情
              </el-button>

              <!-- 只有风险用户才显示启用/禁用按钮 -->
              <template v-if="row.riskUser">
                <el-button
                  size="small"
                  :type="row.status === 1 ? 'danger' : 'success'"
                  @click="toggleUserStatus(row)"
                  class="action-btn"
                >
                  {{ row.status === 1 ? "禁用" : "启用" }}
                </el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="600px">
      <div v-if="selectedUser" class="user-detail">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>用户ID:</label>
              <span>{{ selectedUser.id }}</span>
            </div>
            <div class="detail-item">
              <label>昵称:</label>
              <span>{{ selectedUser.nickname }}</span>
            </div>
            <div class="detail-item">
              <label>手机号:</label>
              <span>{{ selectedUser.phone || "未绑定" }}</span>
            </div>
            <div class="detail-item">
              <label>性别:</label>
              <span>{{ getGenderText(selectedUser.gender) }}</span>
            </div>
            <div class="detail-item">
              <label>用户类型:</label>
              <span>{{
                selectedUser.isLeader === 1 ? "团长" : "普通用户"
              }}</span>
            </div>
            <div class="detail-item">
              <label>积分:</label>
              <span>{{ formatNumber(selectedUser.points) }}</span>
            </div>
            <div class="detail-item">
              <label>OpenID:</label>
              <span>{{ selectedUser.openid || "-" }}</span>
            </div>
            <div class="detail-item">
              <label>UnionID:</label>
              <span>{{ selectedUser.unionid || "-" }}</span>
            </div>
            <div class="detail-item">
              <label>注册时间:</label>
              <span>{{ selectedUser.createdTime }}</span>
            </div>
            <div class="detail-item">
              <label>修改时间:</label>
              <span>{{ selectedUser.modifiedTime || "-" }}</span>
            </div>
          </div>
        </div>

        <div
          v-if="selectedUser.isLeader === 1 && selectedUser.fundAccountVO"
          class="detail-section"
        >
          <h4>资金账户</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>可用余额:</label>
              <span class="balance-text">{{
                formatCurrency(selectedUser.fundAccountVO.balance)
              }}</span>
            </div>
            <div class="detail-item">
              <label>待入账金额:</label>
              <span>{{
                formatCurrency(selectedUser.fundAccountVO.pendingIncome)
              }}</span>
            </div>
            <div class="detail-item">
              <label>退款预留金:</label>
              <span>{{
                formatCurrency(selectedUser.fundAccountVO.refundReserve)
              }}</span>
            </div>
            <div class="detail-item">
              <label>申请提现金额:</label>
              <span>{{
                formatCurrency(selectedUser.fundAccountVO.applyingWithdrawal)
              }}</span>
            </div>
            <div class="detail-item">
              <label>累计收入:</label>
              <span>{{
                formatCurrency(selectedUser.fundAccountVO.totalIncome)
              }}</span>
            </div>
            <div class="detail-item">
              <label>累计提现:</label>
              <span>{{
                formatCurrency(selectedUser.fundAccountVO.totalWithdrawn)
              }}</span>
            </div>
            <div class="detail-item">
              <label>开户时间:</label>
              <span>{{ selectedUser.fundAccountVO.createdTime }}</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { postWithAuth } from "@/utils/request";

// 类型定义
interface FundAccountVO {
  id: string;
  customerId: string;
  pendingIncome: number;
  balance: number;
  refundReserve: number;
  applyingWithdrawal: number;
  totalIncome: number;
  totalWithdrawn: number;
  createdTime: string;
}

interface UserInfo {
  id: string;
  phone: string | null;
  openid: string;
  unionid: string;
  nickname: string;
  gender: number;
  registerSourceId: string;
  avatarUrl: string;
  isLeader: number;
  points: number;
  status: number;
  createdTime: string;
  modifiedTime: string | null;
  riskUser: boolean;
  fundAccountVO: FundAccountVO | null;
}

const loading = ref(false);
const userList = ref<UserInfo[]>([]);
const detailDialogVisible = ref(false);
const selectedUser = ref<UserInfo | null>(null);

// 搜索表单
const searchForm = ref({
  phone: "",
  nickname: "",
  isLeader: "",
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取性别文本
const getGenderText = (gender: number): string => {
  const genderMap: Record<number, string> = {
    0: "未知",
    1: "男",
    2: "女",
  };
  return genderMap[gender] || "未知";
};

// 格式化数字
const formatNumber = (num: number): string => {
  if (num === null || num === undefined) return "0";
  return num.toLocaleString();
};

// 格式化金额
const formatCurrency = (amount: number | null): string => {
  if (amount === null || amount === undefined) return "¥0.00";
  const num = Number(amount);
  if (Number.isNaN(num)) return "¥0.00";
  return `¥${num.toFixed(2)}`;
};

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    const params = {
      phone: searchForm.value.phone || "",
      nickname: searchForm.value.nickname || "",
      isLeader:
        searchForm.value.isLeader === "" ? "" : searchForm.value.isLeader,
      pageIndex: currentPage.value.toString(),
      pageSize: pageSize.value.toString(),
    };

    const res = await postWithAuth("/internal/customer/customers", params);
    if (res.code === 0 && res.data) {
      userList.value = Array.isArray(res.data.list) ? res.data.list : [];
      total.value = Number(res.data.total || 0);
    } else {
      userList.value = [];
      total.value = 0;
      ElMessage.error(res.message || "获取用户列表失败");
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchUserList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    phone: "",
    nickname: "",
    isLeader: "",
  };
  currentPage.value = 1;
  fetchUserList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchUserList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchUserList();
};

// 开通资金账户
const openFundAccount = async (user: UserInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要为用户"${user.nickname}"开通资金账户吗？`,
      "确认开通",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth(
      "/api/internal/customer/openFundAccount",
      {
        customerId: user.id,
      }
    );

    if (response.code === 0) {
      ElMessage.success("资金账户开通成功");
      fetchUserList();
    } else {
      ElMessage.error(response.message || "开通失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("开通资金账户失败:", error);
      ElMessage.error("开通失败");
    }
  }
};

// 查看用户详情
const viewUserDetail = (user: UserInfo) => {
  selectedUser.value = user;
  detailDialogVisible.value = true;
};

// 切换用户状态
const toggleUserStatus = async (user: UserInfo) => {
  const action = user.status === 1 ? "禁用" : "启用";
  const newStatus = user.status === 1 ? 0 : 1;

  try {
    await ElMessageBox.confirm(
      `确定要${action}用户"${user.nickname}"吗？`,
      `确认${action}`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth(
      "/api/internal/customer/enableOrDisable",
      {
        customerId: user.id,
        status: newStatus,
      }
    );

    if (response.code === 0) {
      ElMessage.success(`用户${action}成功`);
      fetchUserList();
    } else {
      ElMessage.error(response.message || `${action}失败`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${action}用户失败:`, error);
      ElMessage.error(`${action}失败`);
    }
  }
};

onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #f3f4f6;
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 200px;
}

.type-select {
  width: 150px;
}

.user-table {
  margin: 0;
}

.no-phone,
.not-applicable {
  color: #9ca3af;
}

.no-account {
  color: #f59e0b;
  font-weight: 500;
}

.points-value {
  font-weight: 600;
  color: #10b981;
}

.balance-value {
  font-weight: 600;
  color: #10b981;
}

.pending-value {
  color: #f59e0b;
}

.applying-value {
  color: #ef4444;
}

.income-value {
  color: #3b82f6;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.action-btn {
  margin: 0;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f3f4f6;
}

.user-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #6b7280;
  width: 100px;
  flex-shrink: 0;
}

.detail-item span {
  color: #1f2937;
}

.balance-text {
  font-weight: 600;
  color: #10b981;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .action-btn {
    width: 100%;
  }
}
</style>
